<?php

namespace Modules\Common\Http\Controllers;

use Api\Service\YidaService;
use Api\Service\YunyangService;
use Catch\CatchAdmin;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Catch\Support\Composer;
use Illuminate\Support\Facades\Redis;
use Modules\Member\Models\Members;
use Modules\Member\Models\MembersProfit;
use Modules\Member\Models\MembersWithdraw;
use Modules\Order\Models\Orders;

/**
 * @group 公共模块
 *
 * @subgroup 服务器信息
 * @subgroupDescription CatchAdmin 后台服务器信息
 */
class ServerController
{
    /**
     * 服务器信息
     *
     * @responseField os string 操作系统
     * @responseField php string PHP版本
     * @responseField laravel string Laravel版本
     * @responseField catchadmin string CatchAdmin版本
     * @responseField host string 域名
     * @responseField mysql string MySQL版本
     * @responseField memory_limit string 内存限制
     * @responseField max_execution_time string 最大执行时间
     * @responseField upload_max_filesize string 上传文件大小
     *
     * @param Request $request
     * @return array
     */
    public function info(Request $request)
    {
        $version = json_decode(json_encode(DB::select('select version()')), true);
        $balance = (new YunyangService())->getBalance();
        $money = 0;
        if (!empty($balance)) {
            $temp = json_decode($balance, true);
            $result = $temp['result'];
            $money = $result['keyong'];
        }
        $yidaBalance= (new YidaService())->getBalance();
        $first = Orders::where('type_code', 3)->sum('money');
        $more = Orders::where('type_code', 3)->sum('overweight_money');
        return [
            'yida_balance' => $yidaBalance,
            'yunyang_balance' => $money,
            'user_balance' => Members::where('status', 1)->sum('price'),
            'order_all' => Orders::where('type_code', 3)->count(),
            'order_money' => bcadd((string)$first, (string)$more),
            'agent_count' => Members::where('status', 1)->where('user_level', '<>', '0')->count(),
            'user_count' => Members::where('status', 1)->count(),
            'os' => PHP_OS_FAMILY,
            'php' => PHP_VERSION,
            'laravel' => app()->version(),
            'catchadmin' => CatchAdmin::version(),
            'host' => $request->host(),
            'mysql' => $version[0]['version()'],
            'memory_limit' => ini_get('memory_limit'),
            'max_execution_time' => ini_get('max_execution_time') . '/S',
            'upload_max_filesize' => ini_get('upload_max_filesize'),
        ];
    }

    public function managerData(Request $request)
    {
        $type = $request->get('type');
        $startTime = $request->get('start_time');
        $endTime = $request->get('end_time');


        $today = [
            Carbon::now()->startOfDay()->timestamp,
            Carbon::now()->endOfDay()->timestamp
        ];

        $yesterday = [
            Carbon::yesterday()->startOfDay()->timestamp,
            Carbon::now()->startOfDay()->timestamp,
        ];
        $seven = [
            Carbon::now()->startOfDay()->copy()->subDays(7)->startOfDay()->timestamp,
            Carbon::now()->timestamp,
        ];
        $month = [
            Carbon::now()->startOfDay()->copy()->subDays(30)->startOfDay()->timestamp,
            Carbon::now()->timestamp,
        ];
        $every = [
            strtotime($startTime),
            strtotime($endTime)
        ];

        $where = match ($type) {
            '1' => $today,
            '2' => $yesterday,
            '3' => $seven,
            '4' => $month,
            '5' => $every,
            default => $today,
        };
        $newCount = Orders::whereBetween('created_at', $where)->count();
        $newCountMoney1 = Orders::whereBetween('created_at', $where)->whereIn('type_code', [1, 2, 3])->sum('money');
        $newCountMoney2 = Orders::whereBetween('overweight_at', $where)->whereIn('type_code', [1, 2, 3])->sum('overweight_money');
        $newCountMoney = bcadd((string)$newCountMoney1, (string)$newCountMoney2,2);
        $agentCount = Redis::get('today_agent_count') ?? 0;
        $memberCount = Members::whereBetween('created_at', $where)->count();
        $withdraw = MembersWithdraw::whereBetween('updated_at', $where)->where('status', 1)->where('type',1)->sum('money'); //总提现
        $profit = MembersProfit::whereBetween('created_at', $where)->where('status',1)->sum('profit');
        $data['new_count'] = $newCount;
        $data['new_count_money'] = $newCountMoney;
        $data['agent_count'] = $agentCount;
        $data['member_count'] = $memberCount;
        $data['withdraw'] = $withdraw;
        $data['profit'] = $profit;
        $data['income'] = 0;
        return $data;
    }

    public function overweightData(Request $request)
    {
        $type = $request->get('type');
        $startTime = $request->get('start_time');
        $endTime = $request->get('end_time');
        $today = [
            Carbon::now()->startOfDay()->timestamp,
            Carbon::now()->endOfDay()->timestamp
        ];

        $yesterday = [
            Carbon::yesterday()->startOfDay()->timestamp,
            Carbon::now()->startOfDay()->timestamp,
        ];
        $seven = [
            Carbon::now()->copy()->subDays(7)->startOfDay(),
            Carbon::now()->timestamp,
        ];
        $month = [
            Carbon::now()->copy()->subDays(30)->startOfDay(),
            Carbon::now()->timestamp,
        ];
        $every = [
            strtotime($startTime),
            strtotime($endTime)
        ];

        $where = match ($type) {
            '1' => $today,
            '2' => $yesterday,
            '3' => $seven,
            '4' => $month,
            '5' => $every,
            default => $today,
        };

        $data = [];
        $data['unpaid_count'] = Orders::whereBetween('overweight_at', $where)->where('is_overweight', 1)->where('overweight_paid_at',0)->count();  //未补数量

        $data['unpaid_money'] = Orders::whereBetween('overweight_at', $where)->where('is_overweight', 1)->where('overweight_paid_at',0)->sum('overweight_money');  //未补订单

        $data['paid_count'] = Orders::whereBetween('overweight_at', $where)->where('is_overweight', 1)->where('overweight_paid_at','<>',0)->count();    //支付超重

        $data['paid_money'] = Orders::whereBetween('overweight_at', $where)->where('is_overweight', 1)->where('overweight_paid_at','<>',0)->sum('overweight_money');    //未支付超重
        return $data;
    }

    public function orderRankList(Request $request)
    {
        $type = $request->get('type');
        $startTime = $request->get('start_time');
        $endTime = $request->get('end_time');


        $today = [
            Carbon::now()->startOfDay()->timestamp,
            Carbon::now()->endOfDay()->timestamp
        ];

        $yesterday = [
            Carbon::yesterday()->startOfDay()->timestamp,
            Carbon::now()->startOfDay()->timestamp,
        ];
        $seven = [
            Carbon::now()->copy()->subDays(7)->startOfDay(),
            Carbon::now()->timestamp,
        ];
        $month = [
            Carbon::now()->copy()->subDays(30)->startOfDay(),
            Carbon::now()->timestamp,
        ];
        $every = [
            strtotime($startTime),
            strtotime($endTime)
        ];

        $where = match ($type) {
            '1' => $today,
            '2' => $yesterday,
            '3' => $seven,
            '4' => $month,
            '5' => $every,
            default => $today,
        };

        return Orders::with('user')->whereBetween('created_at', $where)->whereNotNull('paid_at')->whereIn('type_code', [1, 2, 3])
            ->select(['user_id','created_at','type_code','paid_at',DB::raw('count(*) as count')])->groupBy('user_id')->orderBy('count','desc')->limit(20)->get();
    }

    public function withdrawRankList(Request $request)
    {
        $type = $request->get('type');
        $startTime = $request->get('start_time');
        $endTime = $request->get('end_time');


        $today = [
            Carbon::now()->startOfDay()->timestamp,
            Carbon::now()->endOfDay()->timestamp
        ];

        $yesterday = [
            Carbon::yesterday()->startOfDay()->timestamp,
            Carbon::now()->startOfDay()->timestamp,
        ];
        $seven = [
            Carbon::now()->copy()->subDays(7)->startOfDay(),
            Carbon::now()->timestamp,
        ];
        $month = [
            Carbon::now()->copy()->subDays(30)->startOfDay(),
            Carbon::now()->timestamp,
        ];
        $every = [
            strtotime($startTime),
            strtotime($endTime)
        ];

        $where = match ($type) {
            '1' => $today,
            '2' => $yesterday,
            '3' => $seven,
            '4' => $month,
            '5' => $every,
            default => $today,
        };
        return MembersWithdraw::with('user')->select(['user_id','status','created_at',DB::raw('SUM(money) as withdraw_all')])->whereBetween('created_at', $where)
            ->where('status', '<>', 2)->groupBy('user_id')
            ->orderBy('withdraw_all', 'desc')->limit(20)->get();
    }

    public function areaRankList(Request $request)
    {
        $type = $request->get('type');
        $startTime = $request->get('start_time');
        $endTime = $request->get('end_time');


        $today = [
            Carbon::now()->startOfDay()->timestamp,
            Carbon::now()->endOfDay()->timestamp
        ];

        $yesterday = [
            Carbon::yesterday()->startOfDay()->timestamp,
            Carbon::now()->startOfDay()->timestamp,
        ];
        $seven = [
            Carbon::now()->copy()->subDays(7)->startOfDay(),
            Carbon::now()->timestamp,
        ];
        $month = [
            Carbon::now()->copy()->subDays(30)->startOfDay(),
            Carbon::now()->timestamp,
        ];
        $every = [
            strtotime($startTime),
            strtotime($endTime)
        ];

        $where = match ($type) {
            '1' => $today,
            '2' => $yesterday,
            '3' => $seven,
            '4' => $month,
            '5' => $every,
            default => $today,
        };
        return Orders::whereBetween('created_at', $where)->whereNotNull('paid_at')->whereIn('type_code', [1, 2, 3])->select(['sender_province','created_at','paid_at',DB::raw('count(*) as count')])
            ->orderBy('count','desc')->groupBy('sender_province')->limit(20)->get();
    }
}
